import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userLogin, refreshUserInfo } from '@/api/user'
import type { LoginRequest } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const username = ref('')
  const roles = ref<string[]>([])
  const permissions = ref<string[]>([])
  const isAdmin = ref(false)
  const isLoggedIn = ref(false)

  // 登录
  const login = async (loginForm: LoginRequest) => {
    try {
      const res = await userLogin(loginForm)
      if (res.code === 200) {
        token.value = res.data.accessToken
        username.value = res.data.username
        roles.value = res.data.roles || []
        permissions.value = res.data.permissions || []
        isAdmin.value = roles.value.includes('admin')
        isLoggedIn.value = true
      }
      return res
    } catch (error) {
      console.error('Login error:', error)
      throw error
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      if (!token.value) return null
      const res = await refreshUserInfo(token.value)
      if (res.code === 200) {
        username.value = res.data.username
        roles.value = res.data.roles || []
        permissions.value = res.data.permissions || []
        isAdmin.value = roles.value.includes('admin')
        isLoggedIn.value = true
      }
      return res
    } catch (error) {
      console.error('Get user info error:', error)
      throw error
    }
  }

  // 检查权限
  const hasPermission = (permission: string | string[]): boolean => {
    if (!permission) return true
    if (isAdmin.value) return true // admin 用户拥有所有权限

    const permissionList = Array.isArray(permission) ? permission : [permission]
    return permissionList.some(p => permissions.value.includes(p))
  }

  // 检查角色
  const hasRole = (role: string | string[]): boolean => {
    if (!role) return true
    if (isAdmin.value) return true // admin 用户拥有所有角色权限

    const roleList = Array.isArray(role) ? role : [role]
    return roleList.some(r => roles.value.includes(r))
  }

  // 登出
  const logout = () => {
    token.value = ''
    username.value = ''
    roles.value = []
    permissions.value = []
    isAdmin.value = false
    isLoggedIn.value = false
    localStorage.removeItem('user-store')
    sessionStorage.clear()
  }

  return {
    token,
    username,
    roles,
    permissions,
    isAdmin,
    isLoggedIn,
    login,
    getUserInfo,
    hasPermission,
    hasRole,
    logout
  }
}, {
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token', 'username', 'roles', 'permissions', 'isAdmin', 'isLoggedIn']
  }
})